<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/blog/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="数据结构,读书笔记," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.2" />






<meta name="description" content="栈和队列 栈栈的基本概念栈的概念栈(Stack)：是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。栈顶(Top)：允许进行插入、删除操作的一端，又称为表尾。用栈顶指针(top)来指示栈顶元素。栈底(Bottom)：是固定端，又称为表头。空栈：当表中没有元素时称为空栈。 设栈S">
<meta name="keywords" content="数据结构,读书笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="栈和队列">
<meta property="og:url" content="https://git.oschina.net/choichumgming/blog/2017/12/25/队列与栈/index.html">
<meta property="og:site_name" content="choichumgming&#39;s blog">
<meta property="og:description" content="栈和队列 栈栈的基本概念栈的概念栈(Stack)：是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。栈顶(Top)：允许进行插入、删除操作的一端，又称为表尾。用栈顶指针(top)来指示栈顶元素。栈底(Bottom)：是固定端，又称为表头。空栈：当表中没有元素时称为空栈。 设栈S">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://note.youdao.com/yws/res/1597/WEBRESOURCEa5c6ac93a2ac0ec30d77cc2a452fb8ff">
<meta property="og:image" content="http://note.youdao.com/yws/res/1620/WEBRESOURCEd65d05dde7ee22355219df963d685d4e">
<meta property="og:image" content="http://note.youdao.com/yws/res/1628/WEBRESOURCE03c632c383c693539f3a09b251663907">
<meta property="og:image" content="http://note.youdao.com/yws/res/1633/WEBRESOURCEeed1704f219a8d191c5273fb4b91bc06.png">
<meta property="og:image" content="http://note.youdao.com/yws/res/1640/WEBRESOURCE6b5f2643968a6ea6ed2444e7bd9c9647">
<meta property="og:image" content="http://note.youdao.com/yws/res/1642/WEBRESOURCEdb5b8a8d243367bbba65f38265f406bc">
<meta property="og:image" content="http://note.youdao.com/yws/res/1644/WEBRESOURCEa196a63a905891065e6142fe3fa42969">
<meta property="og:image" content="http://note.youdao.com/yws/res/1646/WEBRESOURCE6194541f6c036e79fe6d165d84cb3abf">
<meta property="og:image" content="http://note.youdao.com/yws/res/1648/WEBRESOURCE6e73fd5969eb44ab22b77f0ded6f8bbc">
<meta property="og:image" content="http://note.youdao.com/yws/res/1659/WEBRESOURCEf45a4650c86de99f5f0ea27468fda67d">
<meta property="og:image" content="http://note.youdao.com/yws/res/1686/WEBRESOURCE8f8d2b81f7517aa3da5d723c7691ad00">
<meta property="og:image" content="http://note.youdao.com/yws/res/1688/WEBRESOURCE00fd097c82d4d5d778cc2247e91f628b">
<meta property="og:updated_time" content="2018-01-08T05:16:00.269Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="栈和队列">
<meta name="twitter:description" content="栈和队列 栈栈的基本概念栈的概念栈(Stack)：是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表。栈顶(Top)：允许进行插入、删除操作的一端，又称为表尾。用栈顶指针(top)来指示栈顶元素。栈底(Bottom)：是固定端，又称为表头。空栈：当表中没有元素时称为空栈。 设栈S">
<meta name="twitter:image" content="http://note.youdao.com/yws/res/1597/WEBRESOURCEa5c6ac93a2ac0ec30d77cc2a452fb8ff">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://git.oschina.net/choichumgming/blog/2017/12/25/队列与栈/"/>





  <title>栈和队列 | choichumgming's blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">choichumgming's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">stay foolish,stay hard</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/blog/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      
        
        <li class="menu-item menu-item-board">
          <a href="/blog/board/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            留言
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://git.oschina.net/choichumgming/blog/blog/2017/12/25/队列与栈/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="choichumgming">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="choichumgming's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">栈和队列</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-12-25T20:44:12+08:00">
                2017-12-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/算法与数据结构/" itemprop="url" rel="index">
                    <span itemprop="name">算法与数据结构</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/blog/2017/12/25/队列与栈/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2017/12/25/队列与栈/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <h1 id="栈和队列"><a href="#栈和队列" class="headerlink" title="栈和队列"></a>栈和队列</h1><hr>
<h2 id="栈"><a href="#栈" class="headerlink" title="栈"></a>栈</h2><h3 id="栈的基本概念"><a href="#栈的基本概念" class="headerlink" title="栈的基本概念"></a>栈的基本概念</h3><h4 id="栈的概念"><a href="#栈的概念" class="headerlink" title="栈的概念"></a>栈的概念</h4><p><strong>栈(Stack)</strong>：<strong>是限制在表的一端进行插入和删除操作的线性表</strong>。又称为<strong>后进先出LIFO (Last In First Out)或先进后出FILO (First In Last Out)线性表</strong>。<br><strong>栈顶(Top)</strong>：允许进行插入、删除操作的一端，又称为表尾。用栈顶指针(top)来指示栈顶元素。<br><strong>栈底(Bottom)</strong>：是固定端，又称为表头。<br><strong>空栈</strong>：当表中没有元素时称为空栈。</p>
<p>设栈S=(a1，a2，…an)，则a1称为栈底元素，an为栈顶元素，如图3-1所示。<br>    栈中元素按a1，a2，…an的次序进栈，退栈的第一个元素应为栈顶元素。即栈的修改是按后进先出的原则进行的。<br><img src="http://note.youdao.com/yws/res/1597/WEBRESOURCEa5c6ac93a2ac0ec30d77cc2a452fb8ff" alt="Alt text"></p>
<h4 id="栈的抽象数据类型定义"><a href="#栈的抽象数据类型定义" class="headerlink" title="栈的抽象数据类型定义"></a>栈的抽象数据类型定义</h4><p>ADT Stack{<br>数据对象：D ={ ai|ai∈ElemSet,  i=1,2,…,n，n≥0 }<br>基本操作：初始化、进栈、出栈、取栈顶元素等<br>} ADT Stack</p>
<h3 id="栈的顺序存储表示"><a href="#栈的顺序存储表示" class="headerlink" title="栈的顺序存储表示"></a>栈的顺序存储表示</h3><p>栈的顺序存储结构简称为顺序栈，和线性表相类似，用<strong>一维数组</strong>来存储栈。<br>根据数组是否可以根据需要增大，又可分为<strong>静态顺序栈</strong>和<strong>动态顺序栈</strong>。<br> 静态顺序栈实现简单，但不能根据需要增大栈的存储空间；<br><strong>动态顺序栈</strong>可以根据需要增大栈的存储空间，但实现稍为复杂</p>
<h4 id="栈的动态顺序存储表示"><a href="#栈的动态顺序存储表示" class="headerlink" title="栈的动态顺序存储表示"></a>栈的动态顺序存储表示</h4><p>采用<strong>动态一维数组（java中可以用arraylist）</strong>来存储栈。所谓动态，指的是栈的大小可以根据需要增加。<br><strong>要点：</strong></p>
<ul>
<li>用bottom表示栈底指针，栈底固定不变的；栈顶则随着进栈和退栈操作而变化。用top(称为栈顶指针)指示当前栈顶位置。</li>
<li>用top=bottom作为栈空的标记，每次top指向栈顶数组中的下一个存储位置。</li>
<li>结点进栈：首先将数据元素保存到栈顶(top所指的当前位置)，然后执行top加1，使top指向栈顶的下一个存储位置;</li>
<li>结点出栈：首先执行top减1，使top指向栈顶元素的存储位置，然后将栈顶元素取出。<br><img src="http://note.youdao.com/yws/res/1620/WEBRESOURCEd65d05dde7ee22355219df963d685d4e" alt="Alt text"><br><br><h4 id="栈的静态顺序存储表示"><a href="#栈的静态顺序存储表示" class="headerlink" title="栈的静态顺序存储表示"></a>栈的静态顺序存储表示</h4>采用静态一维数组来存储栈。</li>
<li><strong>栈底固定不变的</strong>；栈顶则随着进栈和退栈操作而变化，用一个整型变量top(称为栈顶指针)来指示当前栈顶位置。</li>
<li>用<strong>top=0表示栈空的初始状态</strong>，每次top指向栈顶在数组中的存储位置。</li>
<li><strong>结点进栈</strong>：首先执行top加1，使top指向新的栈顶位置，然后将数据元素保存到栈顶(top所指的当前位置)。</li>
<li><strong>结点出栈</strong>：首先把top指向的栈顶元素取出，然后执行top减1，使top指向新的栈顶位置<br><img src="http://note.youdao.com/yws/res/1628/WEBRESOURCE03c632c383c693539f3a09b251663907" alt="Alt text"><h3 id="栈的链式存储表示"><a href="#栈的链式存储表示" class="headerlink" title="栈的链式存储表示"></a>栈的链式存储表示</h3>栈的链式存储结构称为链栈，是<strong>运算受限的单链表</strong>。其插入和删除操作<strong>只能在表头位置</strong>上进行。因此，链栈没有必要像单链表那样附加头结点，栈顶指针top就是链表的头指针。<br><img src="http://note.youdao.com/yws/res/1633/WEBRESOURCEeed1704f219a8d191c5273fb4b91bc06.png" alt="Alt text"></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//关键代码</span></div><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LinkStack</span></span></div><div class="line"><span class="class"></span>&#123;   <span class="keyword">private</span> Node top;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">push</span><span class="params">(Object obj)</span></span>&#123;&#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">pop</span><span class="params">()</span></span>&#123;&#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">peek</span><span class="params">()</span></span>&#123;&#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isEmpty</span><span class="params">()</span></span>&#123;&#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">clear</span><span class="params">()</span></span>&#123;&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h3 id="栈的应用（表达式求值）"><a href="#栈的应用（表达式求值）" class="headerlink" title="栈的应用（表达式求值）"></a>栈的应用（表达式求值）</h3><p><img src="http://note.youdao.com/yws/res/1640/WEBRESOURCE6b5f2643968a6ea6ed2444e7bd9c9647" alt="Alt text"><br><img src="http://note.youdao.com/yws/res/1642/WEBRESOURCEdb5b8a8d243367bbba65f38265f406bc" alt="Alt text"><br><img src="http://note.youdao.com/yws/res/1644/WEBRESOURCEa196a63a905891065e6142fe3fa42969" alt="Alt text"><br><img src="http://note.youdao.com/yws/res/1646/WEBRESOURCE6194541f6c036e79fe6d165d84cb3abf" alt="Alt text"><br><img src="http://note.youdao.com/yws/res/1648/WEBRESOURCE6e73fd5969eb44ab22b77f0ded6f8bbc" alt="Alt text"></p>
<h2 id="队列"><a href="#队列" class="headerlink" title="队列"></a>队列</h2><h3 id="队列的基本概念"><a href="#队列的基本概念" class="headerlink" title="队列的基本概念"></a>队列的基本概念</h3><p> <strong>队列(Queue)</strong>：也是<strong>运算受限的线性表</strong>。是一种<strong>先进先出(First In First Out ，简称FIFO)</strong>的线性表。只允许在表的<strong>一端进行插入，而在另一端进行删除</strong>。<br> <strong>队首(front)</strong> ：允许进行删除的一端称为队首。<br><strong>队尾(rear)</strong> ：允许进行插入的一端称为队尾。、<br>队列中没有元素时称为空队列。在空队列中依次加入元素a1, a2, …, an之后，a1是队首元素，an是队尾元素。显然退出队列的次序也只能是a1, a2, …, an ，即队列的修改是依先进先出的原则进行的。<br><img src="http://note.youdao.com/yws/res/1659/WEBRESOURCEf45a4650c86de99f5f0ea27468fda67d" alt="Alt text"></p>
<h3 id="队列的顺序表示和实现"><a href="#队列的顺序表示和实现" class="headerlink" title="队列的顺序表示和实现"></a>队列的顺序表示和实现</h3><p>利用一组连续的存储单元(一维数组) 依次存放从队首到队尾的各个元素，称为顺序队列。<br>对于队列，和顺序栈相类似，也有动态和静态之分。</p>
<h4 id="队列的顺序存储结构"><a href="#队列的顺序存储结构" class="headerlink" title="队列的顺序存储结构"></a>队列的顺序存储结构</h4><p>设立一个队首指针front ，一个队尾指针rear ，分别指向队首和队尾元素。<br> ◆ 初始化：front=rear=0。<br> ◆ 入队：将新元素插入rear所指的位置，然后rear加1。<br> ◆ 出队：删去front所指的元素，然后加1并返回被删元素。<br> ◆ 队列为空：front=rear。<br>◆ 队满：rear=MAX_QUEUE_SIZE-1或front=rear。<br>在非空队列里，<strong>队首指针始终指向队头元素，而队尾指针始终指向队尾元素的下一位置。</strong></p>
<p>顺序队列中存在“<strong>假溢出</strong>”现象。因为在入队和出队操作中，<strong>头、尾指针只增加不减小</strong>，致使被删除元素的空间永远无法重新利用。因此，尽管队列中实际元素个数可能远远小于数组大小，但可能由于尾指针巳超出向量空间的上界而不能做入队操作。该现象称为<strong>假溢出</strong></p>
<h5 id="循环队列"><a href="#循环队列" class="headerlink" title="循环队列"></a>循环队列</h5><p>为充分利用向量空间，克服上述“<strong>假溢出</strong>”现象的方法是：将为<strong>队列分配的向量空间看成为一个首尾相接的圆环</strong>，并称这种队列为<strong>循环队列(Circular Queu</strong>e)。<br>在循环队列中进行出队、入队操作时，队首、队尾指针仍要加1，朝前移动。只不过当队首、队尾指针指向向量上界(MAX_QUEUE_SIZE-1)时，其加1操作的结果是指向向量的下界0。这种循环意义下的加1操作可以描述为：<strong>i=(i+1)%MAX_QUEUE_SIZE ;</strong><br>其中： i代表队首指针(front)或队尾指针(rear)<br>显然，为循环队列所分配的空间可以被充分利用，除非向量空间真的被队列元素全部占用，否则不会上溢。因此，真正实用的顺序队列是循环队列。<br><img src="http://note.youdao.com/yws/res/1686/WEBRESOURCE8f8d2b81f7517aa3da5d723c7691ad00" alt="Alt text"><br><img src="http://note.youdao.com/yws/res/1688/WEBRESOURCE00fd097c82d4d5d778cc2247e91f628b" alt="Alt text"></p>
<p><strong>但是这时候会出现一个问题</strong>：入队时尾指针向前追赶头指针，出队时头指针向前追赶尾指针，故队空和队满时头尾指针均相等。<strong>因此，无法通过front=rear来判断队列“空”还是“满”。</strong><br>解决此问题的方法是：约定<strong>入队前</strong>，测试尾指针在循环意义下加1<strong>后是否等于头指针，若相等则认为队满</strong>。即：<br> rear所指的单元始终为空。<br>循环队列为空：front=rear 。<br>循环队列满：(rear+1)%MAX_QUEUE_SIZE =front。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div></pre></td><td class="code"><pre><div class="line"><span class="comment">/*</span></div><div class="line"><span class="comment">*宽度优先中的使用linkedlist作为队列进行元素的操作</span></div><div class="line"><span class="comment">*/</span></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">bfs</span><span class="params">(String str)</span> </span>&#123;</div><div class="line">        <span class="comment">// TODO Auto-generated method stub</span></div><div class="line">        que=<span class="keyword">new</span>  LinkedList&lt;String&gt;();</div><div class="line">        que.add(str);</div><div class="line">        map.put(str, <span class="number">0</span>);</div><div class="line">        </div><div class="line">        <span class="keyword">int</span> a = str.indexOf(<span class="string">"A"</span>);</div><div class="line">        <span class="keyword">int</span> b = str.indexOf(<span class="string">"B"</span>);<span class="comment">//获取a和b的下标</span></div><div class="line">        </div><div class="line">        <span class="keyword">while</span>(!que.isEmpty())&#123;</div><div class="line">            String s=que.poll();</div><div class="line">            </div><div class="line">            </div><div class="line">            <span class="keyword">if</span>(s.indexOf(<span class="string">'A'</span>)==b &amp;&amp; s.indexOf(<span class="string">'B'</span>)==a)&#123;<span class="comment">//当位置交换时</span></div><div class="line">                System.out.println(map.get(s));<span class="comment">//从map中获取步数</span></div><div class="line">                <span class="keyword">return</span>;</div><div class="line">            &#125;</div><div class="line">             <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++)&#123;</div><div class="line">                 <span class="keyword">int</span> space =s.indexOf(<span class="string">" "</span>);</div><div class="line">                 <span class="keyword">int</span> x =space/ <span class="number">3</span>;<span class="keyword">int</span> y = space % <span class="number">3</span>;<span class="comment">//获得空格的x坐标</span></div><div class="line">                 <span class="keyword">int</span> tx = x + dir[i][<span class="number">0</span>];</div><div class="line">                  <span class="keyword">int</span> ty =y + dir[i][<span class="number">1</span>];</div><div class="line">                  <span class="keyword">if</span>(tx &gt;=<span class="number">0</span> &amp;&amp; tx &lt;= <span class="number">1</span> &amp;&amp; ty &gt;=<span class="number">0</span> &amp;&amp; ty &lt;= <span class="number">2</span>)&#123;</div><div class="line">                      <span class="keyword">char</span> []ch=s.toCharArray();</div><div class="line">                      </div><div class="line">                        <span class="keyword">char</span> charT = ch[x * <span class="number">3</span> + y];</div><div class="line">                        ch[x * <span class="number">3</span> + y] = ch[tx * <span class="number">3</span> + ty];</div><div class="line">                        ch[tx * <span class="number">3</span> + ty] = charT;</div><div class="line">                      String ss=String.valueOf(ch);</div><div class="line">                      </div><div class="line">                      <span class="keyword">if</span>(!map.containsKey(ss))&#123;       </div><div class="line">                          map.put(ss, map.get(s)+<span class="number">1</span>);</div><div class="line">                          que.add(ss);</div><div class="line">                      &#125;</div><div class="line">                  &#125;</div><div class="line">             &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/数据结构/" rel="tag"># 数据结构</a>
          
            <a href="/blog/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/12/25/图/" rel="next" title="图">
                <i class="fa fa-chevron-left"></i> 图
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/12/26/AVL平衡二叉搜索树/" rel="prev" title="AVL平衡二叉搜索树">
                AVL平衡二叉搜索树 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <!--PC版-->
<div id="SOHUCS" ></div>


    

  </div>
     <div class="comments" id="comments">
       
     </div>
   





        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/avatar.gif"
               alt="choichumgming" />
          <p class="site-author-name" itemprop="name">choichumgming</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives/">
                <span class="site-state-item-count">15</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              
                <span class="site-state-item-count">6</span>
                <span class="site-state-item-name">标签</span>
              
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://www.weibo.com/u/2558763801" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                    
                      微博
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#栈和队列"><span class="nav-number">1.</span> <span class="nav-text">栈和队列</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#栈"><span class="nav-number">1.1.</span> <span class="nav-text">栈</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#栈的基本概念"><span class="nav-number">1.1.1.</span> <span class="nav-text">栈的基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#栈的概念"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">栈的概念</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#栈的抽象数据类型定义"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">栈的抽象数据类型定义</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#栈的顺序存储表示"><span class="nav-number">1.1.2.</span> <span class="nav-text">栈的顺序存储表示</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#栈的动态顺序存储表示"><span class="nav-number">1.1.2.1.</span> <span class="nav-text">栈的动态顺序存储表示</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#栈的静态顺序存储表示"><span class="nav-number">1.1.2.2.</span> <span class="nav-text">栈的静态顺序存储表示</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#栈的链式存储表示"><span class="nav-number">1.1.3.</span> <span class="nav-text">栈的链式存储表示</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#栈的应用（表达式求值）"><span class="nav-number">1.1.4.</span> <span class="nav-text">栈的应用（表达式求值）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#队列"><span class="nav-number">1.2.</span> <span class="nav-text">队列</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#队列的基本概念"><span class="nav-number">1.2.1.</span> <span class="nav-text">队列的基本概念</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#队列的顺序表示和实现"><span class="nav-number">1.2.2.</span> <span class="nav-text">队列的顺序表示和实现</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#队列的顺序存储结构"><span class="nav-number">1.2.2.1.</span> <span class="nav-text">队列的顺序存储结构</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#循环队列"><span class="nav-number">1.2.2.1.1.</span> <span class="nav-text">循环队列</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">choichumgming</span>

  
</div>


  <div class="powered-by">
    由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
  </div>

  <span class="post-meta-divider">|</span>

  <div class="theme-info">
    主题 &mdash;
    <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
      NexT.Gemini
    </a>
  </div>


        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.2"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  




  
    <script type="text/javascript">
    (function(){
      var appid = 'cytnT5dky';
      var conf = '56c170b7352bd027682e3707e9eb5071';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>
  





  





  

  

  

  

  

  

</body>
</html>
